import 'dart:io';
import 'dart:math';
import 'dart:typed_data';
import 'dart:ui';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:xsdk_flutter/xsdk/framework/base/xsdk_function.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_color.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_jiami.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_number.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_style.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_widget.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:photo_view/photo_view.dart';

import '../operation/x_constant_temp.dart';
/*
其他:
https://pub-web.flutter-io.cn/packages/lottie


图片压缩:
https://pub-web.flutter-io.cn/packages/image_compression/install
https://pub-web.flutter-io.cn/packages/flutter_image_compress


保存图片到相册
https://pub-web.flutter-io.cn/packages/image_gallery_saver_plus
dependencies:
  image_gallery_saver_plus: ^4.0.1

  或 image_gallery_saver 有flutter鸿蒙版

 */

abstract class XImageUtils{


  /*
  图片压缩:
  https://pub-web.flutter-io.cn/packages/flutter_image_compress
  dependencies:
    flutter_image_compress: <latest_version>
  import 'package:flutter_image_compress/flutter_image_compress.dart';
   */
  static Future<Uint8List?> compressFileImageToUint8List(
      {
        required String filePath,
        int minWidth=500,
        int minHeight=500,
        int quality=80,
        
      }
      ) async{
    File file=File(filePath);
    if(file.existsSync()){
      Uint8List? result = await FlutterImageCompress.compressWithFile(
        filePath,
        minWidth: XNumberUtils.d2int(minWidth*XTempData.deviceScreenScale),
        minHeight: XNumberUtils.d2int(minHeight*XTempData.deviceScreenScale),
        quality: quality,
      );
      return result;

    }

    return null;
  }

  static Future<String?> compressFileImageToNewFilePath(
      {
        required String filePath,
        required String targetPath,
        int minWidth=500,
        int minHeight=500,
        int quality=80,
        
      }
      ) async{
    File file=File(filePath); //file.readAsBytes()

    if(file.existsSync()){
      XFile? result = await FlutterImageCompress.compressAndGetFile(
        filePath,
        targetPath,
        minWidth: XNumberUtils.d2int(minWidth*XTempData.deviceScreenScale),
        minHeight: XNumberUtils.d2int(minHeight*XTempData.deviceScreenScale),
        quality: quality,
      );
      return result?.path;//result.readAsBytes();

    }

    return null;
  }


  /*
  显示图片,支持放大缩小
  图片浏览:
  https://pub.flutter-io.cn/packages/photo_view
  dependencies:
    photo_view: ^0.15.0
  import 'package:photo_view/photo_view.dart';
   */
  static Widget getPhotoViewWithAsset(
      String assetImageName, //'welcome_app.png'
          {
        Color? backgroundColor=XColorUtils.colorF8F8F8,
      }
      ){
    return PhotoView(
        backgroundDecoration:backgroundColor==null?null:XWidgetUtils.getBoxDecoration(
          backgroundColor: backgroundColor,
        ),
        imageProvider: AssetImage('assets/images/$assetImageName')
    );
  }
  static Widget getPhotoViewWithUrl(
      String imageUrl,
      {
        Color? backgroundColor=XColorUtils.colorF8F8F8,
      }
      ){
    return PhotoView(
        backgroundDecoration:backgroundColor==null?null:XWidgetUtils.getBoxDecoration(
          backgroundColor: backgroundColor,
        ),
        imageProvider: CachedNetworkImageProvider(imageUrl)
    );
  }
  static Widget getPhotoViewWithFile(
      String imageFilePath,
      {
        Color? backgroundColor=XColorUtils.colorF8F8F8, //PhotoView默认是黑色
      }
      ){
    return PhotoView(
        backgroundDecoration:backgroundColor==null?null:XWidgetUtils.getBoxDecoration(
          backgroundColor: backgroundColor,
        ),
        imageProvider:  FileImage(File(imageFilePath), scale: 1)
    );
  }

  /*
  加载svg图片:
  https://pub-web.flutter-io.cn/packages/flutter_svg/install
  dependencies:
    flutter_svg: ^2.0.10+1
  import 'package:flutter_svg/flutter_svg.dart';

  其他: https://pub-web.flutter-io.cn/packages/flutter_svg_provider

   */
  static Widget getSVGWidgetWithAsset(
      String assetSVGName, //'welcome_app.svg'
          {
        double? width,
        double? height,
        Color? color,
        BoxFit fit=BoxFit.cover,
        
      }
      ){
    return SvgPicture.asset(
      'assets/images/$assetSVGName',
      fit: fit,//显示效果 例如: BoxFit.cover cover:自适应 fill:铺满可能变形 fitWidth:宽充满 filHright:高充满 repeat:多张图片平铺
      //alignment: ,//图片相对容器的对齐方式 例如: Alignment.bottomRight
      //centerSlice:,//保留区域 例如：Rect.fromLTRB(9, 27, 60, 27 + 1.0)
      //repeat: ImageRepeat.noRepeat,//图片重复模式 ImageRepeat
      //colorBlendMode: ,//图片混合模式 BlendMode.colorBurn
      width: width==null?width:width*XTempData.deviceScreenScale,
      height: height==null?height:height*XTempData.deviceScreenScale,
      colorFilter: color==null?null:ColorFilter.mode(color, BlendMode.srcIn),
    );

  }
  static Widget getSVGWidgetWithUrl(
      String url,
      {
        double? width,
        double? height,
        Color? color,
        BoxFit fit=BoxFit.cover,
        
      }
      ){
    return SvgPicture.network(
      url,
      fit: fit,//显示效果 例如: BoxFit.cover cover:自适应 fill:铺满可能变形 fitWidth:宽充满 filHright:高充满 repeat:多张图片平铺
      //alignment: ,//图片相对容器的对齐方式 例如: Alignment.bottomRight
      //centerSlice:,//保留区域 例如：Rect.fromLTRB(9, 27, 60, 27 + 1.0)
      //repeat: ImageRepeat.noRepeat,//图片重复模式 ImageRepeat
      //colorBlendMode: ,//图片混合模式 BlendMode.colorBurn
      width: width==null?width:width*XTempData.deviceScreenScale,
      height: height==null?height:height*XTempData.deviceScreenScale,
      colorFilter: color==null?null:ColorFilter.mode(color, BlendMode.srcIn),
      placeholderBuilder: (BuildContext context) => Container(
          padding: const EdgeInsets.all(30.0),
          child: const CircularProgressIndicator()),
    );

  }

  //String rawSvg = '''<svg ...>...</svg>''';
//   static Widget getSVGWidgetWithCode(
//       String rawSvg,
//       {
//         required int width,
//         required int height,
//         Color? color,
//         BoxFit fit=BoxFit.cover,
//       }
//       ) async{
//
//     final String rawSvg = '''<svg ...>...</svg>''';
//     final PictureInfo pictureInfo = await vg.loadPicture(SvgStringLoader(rawSvg), null);
//
// // You can draw the picture to a canvas:
//     //canvas.drawPicture(pictureInfo.picture);
//
// // Or convert the picture to an image:
//     final ui.Image image = await pictureInfo.picture.toImage(width,height);
//
//     pictureInfo.picture.dispose();
//
//     return image;
//
//   }

  /*
  (支持圆角或圆形)图片加载(网络,缓存): https://pub.dev/packages/cached_network_image
  依赖:
  dependencies:
    cached_network_image: ^3.3.1
  引入:
  import 'package:cached_network_image/cached_network_image.dart';


  CachedNetworkImage(
        imageUrl: "http://via.placeholder.com/350x150",
        placeholder: (context, url) => CircularProgressIndicator(),
        errorWidget: (context, url, error) => Icon(Icons.error),
     )

    CachedNetworkImage(
  imageUrl: "http://via.placeholder.com/200x150",
  imageBuilder: (context, imageProvider) => Container(
    decoration: BoxDecoration(
      image: DecorationImage(
          image: imageProvider,
          fit: BoxFit.cover,
          colorFilter:
              ColorFilter.mode(Colors.red, BlendMode.colorBurn)),
    ),
  ),
  placeholder: (context, url) => CircularProgressIndicator(),
  errorWidget: (context, url, error) => Icon(Icons.error),
)

 */

  static Widget getImageWidgetWithUrl(
      {
        Color? backgroundColor,
        double borderWidth=1,
        required double width,
        required double height,
        required String imageUrl,
        required String defaultImageAssetName,
        double radius=5,//圆角半径
        bool isCircle=false,// false为矩形, true为圆形
        BoxFit imgFix=BoxFit.cover,
        
      }
      ){

    //加载网络图片,支持gif动画,没有占位图功能,加载完后,直接显示
    // return Image.network(url);

    return XWidgetUtils.getLayoutContainer(
        padding: XWidgetUtils.getEdgeInsets(borderWidth, borderWidth, borderWidth, borderWidth),
        decoration: BoxDecoration(
          color: backgroundColor,
          borderRadius: isCircle?null:BorderRadius.all(Radius.circular(radius)),
          shape:isCircle?BoxShape.circle:BoxShape.rectangle,
        ),
        child: CachedNetworkImage(
          width: width*XTempData.deviceScreenScale-borderWidth,
          height: height*XTempData.deviceScreenScale-borderWidth,
          imageUrl: imageUrl,
          imageBuilder: (
              BuildContext context,
              ImageProvider imageProvider){
            return XWidgetUtils.getLayoutContainer(
                decoration: BoxDecoration(
                    borderRadius: isCircle?null:BorderRadius.all(Radius.circular(radius)),
                    shape:isCircle?BoxShape.circle:BoxShape.rectangle,
                    image: DecorationImage(
                      image: imageProvider,
                      fit: imgFix,
                    )
                )
            );
          },
          placeholder: (context, url) => XWidgetUtils.getLayoutContainer(
              decoration: BoxDecoration(
                  borderRadius: isCircle?null:BorderRadius.all(Radius.circular(radius)),
                  shape:isCircle?BoxShape.circle:BoxShape.rectangle,
                  image: DecorationImage(
                    image: AssetImage('assets/images/$defaultImageAssetName'),
                    fit: BoxFit.cover,
                    //colorFilter:ColorFilter.mode(Colors.red, BlendMode.colorBurn)),
                  )
              )
          ),
          errorWidget: (context, url, error) => XWidgetUtils.getLayoutContainer(
              decoration: BoxDecoration(
                  borderRadius: isCircle?null:BorderRadius.all(Radius.circular(radius)),
                  shape:isCircle?BoxShape.circle:BoxShape.rectangle,
                  image: DecorationImage(
                    image: AssetImage('assets/images/$defaultImageAssetName'),
                    fit: BoxFit.cover,
                    //colorFilter:ColorFilter.mode(Colors.red, BlendMode.colorBurn)),
                  )
              )
          ),
        )
    );
  }




  /*
  本地图片素材
在pubspec.yaml添加图片路径,如:
flutter:
  assets:
    # Add assets from the images directory to the application.
    - assets/images/

XImageUtils.getImageWidgetWithAsset(
          'welcome_app.png',
          width: 122,
          height: 32.5
      )
   */
  static Image getImageWidgetWithAsset(
      String assetImageName, //'welcome_app.png'
          {
        double? width,
        double? height,
        Color? color,
        BoxFit fit=BoxFit.cover,
        
      }
      ){
    return Image.asset(
      'assets/images/$assetImageName',
      fit: fit,//显示效果 例如: BoxFit.cover cover:自适应 fill:铺满可能变形 fitWidth:宽充满 filHright:高充满 repeat:多张图片平铺
      //alignment: ,//图片相对容器的对齐方式 例如: Alignment.bottomRight
      //centerSlice:,//保留区域 例如：Rect.fromLTRB(9, 27, 60, 27 + 1.0)
      //repeat: ImageRepeat.noRepeat,//图片重复模式 ImageRepeat
      //colorBlendMode: ,//图片混合模式 BlendMode.colorBurn
      width: width==null?width:width*XTempData.deviceScreenScale,
      height: height==null?height:height*XTempData.deviceScreenScale,
      color: color,
    );

  }

  /*
  加载外储存卡(硬盘)图片
   */
  static Image getImageWidgetWithFile(
      String imageFilePath,
      {
        double? width,
        double? height,
        Color? color,
        BoxFit fit=BoxFit.cover,//显示效果 例如: BoxFit.cover cover:自适应 fill:铺满可能变形 fitWidth:宽充满 filHright:高充满 repeat:多张图片平铺
        
      }
      ){
    return Image.file(
      File(imageFilePath),
      fit: fit,
      //alignment: ,//图片相对容器的对齐方式 例如: Alignment.bottomRight
      //centerSlice:,//保留区域 例如：Rect.fromLTRB(9, 27, 60, 27 + 1.0)
      //repeat: ImageRepeat.noRepeat,//图片重复模式 ImageRepeat
      //colorBlendMode: ,//图片混合模式 BlendMode.colorBurn
      width: width==null?width:width*XTempData.deviceScreenScale,
      height: height==null?height:height*XTempData.deviceScreenScale,
      color: color,
    );

  }


  static Image getImageWithBase64(String base64Str){
    Uint8List imageBytes = XJiamiUtils.base64ToUint8List(base64Str);
    return Image.memory(imageBytes);
  }


  //获得宽和高
  static void getImageInfo(
      {
        Uint8List? imageBytes,
        String? base64Str,
        required XFunctionResultCallback<Map<String,dynamic>> callback,
      }
      ){

    if(imageBytes==null){
      if(base64Str!=null){
        imageBytes = XJiamiUtils.base64ToUint8List(base64Str);
      }
    }

    if(imageBytes!=null){
      MemoryImage memoryImage=MemoryImage(imageBytes);
      memoryImage.resolve(ImageConfiguration()).addListener(ImageStreamListener(
              (info,_){
            Map<String,dynamic> res={};
            res['width']=info.image.width;
            res['height']=info.image.height;
            callback(res);
          }
      ));
    }else{
      Map<String,dynamic> res={};
      res['width']=0;
      res['height']=0;
      callback(res);
    }

  }

  //Icon////////////////////////////////////////////////////////////////////

  /*
  DecorationImage(//设置图片背景，设置image需要一个DecorationImage类
                // Load image from assets
                  image: AssetImage('images/base_widgets/icon_main_date_select@2x.png'),
                  // Make the image cover the whole area
                  fit: BoxFit.cover))
   */


  //本地系统自带图标素材 Icons.directions_car Icons.directions_bus,...
  //icon: Icon(Icons.home, color: _BottomNavigationColor,size:36),
  //IconButton
  static Icon getIconWidget(
      {
        required IconData Icons_icon,
        Color? color,
        double? size,
      }

      ){

    return Icon(
      Icons_icon,
      color: color,
      size: size,
    );
  }


  static ImageIcon getImageIconWidget(
      String assetImageName, //'welcome_app.png',
          {
        Color? color,
        double? size,
        
      }

      ){

    return ImageIcon(
      AssetImage('assets/images/$assetImageName',),
      color: color,
      size: size==null?size:size*XTempData.deviceScreenScale,
    );
  }



//获得图片像素点颜色(注意:这里Image并非widget的image)
//https://www.jianshu.com/p/ffb4b58f0aa9/
//https://www.learnfk.com/question/flutter/71197408.html

// static Future<Color> getPixelColors(ui.Image img) async {
//   ByteData? byteData = await img.toByteData(format: ui.ImageByteFormat.png);
//   Codec codec = await ui.instantiateImageCodec(byteData!.buffer.asUint8List());
//   FrameInfo frame = await codec.getNextFrame();
//   ByteData? byteData2 = await frame.image.toByteData(format: ui.ImageByteFormat.png);
//   var color = byteData2.getPixel(100, 100);
//   print(color);
//   return color;
// }



//添加水印////////////////////////////////////////////////////////////////////////

  // 图片加文字
  static Future<Uint8List> getImageAddTextWaterMarkAtLeftBottom(
      {
        required Uint8List imageListData,
        required String text,
        double fontSize=30,
        Color fontColor=Colors.grey,
        FontWeight fontWeight=FontWeight.normal
      }
      ) async {

    // 创建画布和图片
    PictureRecorder recorder = PictureRecorder();
    Canvas canvas = Canvas(recorder);

    // 加载图片对象 ui.Image
    Codec codec = await instantiateImageCodec(imageListData);
    FrameInfo frame = await codec.getNextFrame();
    dynamic image = frame.image;//ui.Image
    int width = image.width;
    int height = image.height;

    // 绘制原始图片到画布上
    canvas.drawImage(image, const Offset(0, 0), Paint());

    // 准备水印文本
    canvas.saveLayer(
        Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble()),
        Paint()..blendMode = BlendMode.multiply);

    // 计算对角线长度
    // double dimension = sqrt(pow(image.width, 2) + pow(image.height, 2));
    // // 计算水印文本重复次数
    // var rectSize = pow(dimension, 2);
    // int textRepeating = ((rectSize / pow(30, 2) * 2) / (text.length + 8)).round();
    //
    // // 设置水印文本位置和样式
    // Point pivotPoint = Point(dimension / 2, dimension / 2);
    // canvas.translate(pivotPoint.x.toDouble(), pivotPoint.y.toDouble());
    // canvas.rotate(-25 * pi / 180);
    // canvas.translate(
    //     -pivotPoint.distanceTo(Point(0, image.height)),
    //     -pivotPoint.distanceTo(const Point(0, 0)));

    var textPainter = TextPainter(
      text: TextSpan(
          text: text,//(text.padRight(text.length + 8)) * textRepeating,
          style: XStyleUtils.getTextStyle(
            fontSize: fontSize,
            color: fontColor,
            fontWeight: fontWeight,
          )
      ),
      maxLines: 1,
      textDirection: TextDirection.ltr,
      textAlign: TextAlign.start,
    );
    textPainter.layout(maxWidth: width.toDouble());
    textPainter.paint(canvas, Offset(15,height-15-fontSize));

    canvas.restore();

    // 获取处理后的图片
    Picture picture = recorder.endRecording();
    final img = await picture.toImage(width.toInt(), height.toInt());

    // 转换为 Uint8List
    final pngBytes = await img.toByteData(format: ImageByteFormat.png);
    return pngBytes!.buffer.asUint8List();
  }



  //文字倾斜,铺满整个图片
  static Future<Uint8List> imageAddWaterMark(
      {
        required Uint8List imageListData,
        required String text,
        double fontSize=30,
        Color fontColor=Colors.grey,
        FontWeight fontWeight=FontWeight.normal
      }
      ) async {

    // 创建画布和图片
    PictureRecorder recorder = PictureRecorder();
    Canvas canvas = Canvas(recorder);

    // 加载图片对象 ui.Image
    Codec codec = await instantiateImageCodec(imageListData);
    FrameInfo frame = await codec.getNextFrame();
    dynamic image = frame.image;//ui.Image
    int width = image.width;
    int height = image.height;

    // 绘制原始图片到画布上
    canvas.drawImage(image, const Offset(0, 0), Paint());

    // 准备水印文本
    canvas.saveLayer(
        Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble()),
        Paint()..blendMode = BlendMode.multiply);

    // 计算对角线长度
    double dimension = sqrt(pow(image.width, 2) + pow(image.height, 2));

    // 计算水印文本重复次数
    var rectSize = pow(dimension, 2);
    int textRepeating = ((rectSize / pow(30, 2) * 2) / (text.length + 8))
        .round();

    // 设置水印文本位置和样式
    Point pivotPoint = Point(dimension / 2, dimension / 2);
    canvas.translate(pivotPoint.x.toDouble(), pivotPoint.y.toDouble());
    canvas.rotate(-25 * pi / 180);
    canvas.translate(
        -pivotPoint.distanceTo(Point(0, image.height)),
        -pivotPoint.distanceTo(const Point(0, 0)));

    var textPainter = TextPainter(
      text: TextSpan(
          text: (text.padRight(text.length + 8)) * textRepeating,
          style: TextStyle(
              fontSize: fontSize,
              color: fontColor,
              height: 2
          )
      ),
      maxLines: 1,
      textDirection: TextDirection.ltr,
      textAlign: TextAlign.start,
    );
    textPainter.layout(maxWidth: dimension);
    textPainter.paint(canvas, Offset.zero);

    canvas.restore();

    // 获取处理后的图片
    Picture picture = recorder.endRecording();
    final img = await picture.toImage(width.toInt(), height.toInt());

    // 转换为 Uint8List
    final pngBytes = await img.toByteData(format: ImageByteFormat.png);
    return pngBytes!.buffer.asUint8List();
  }

  /*
  保存图片到相册
  https://pub-web.flutter-io.cn/packages/image_gallery_saver_plus

  https://pub-web.flutter-io.cn/packages/image_gallery_saver
  image_gallery_saver: ^2.0.3 有鸿蒙版



_saveNetworkImage() async {
    var response = await Dio().get(
        "https://ss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=a62e824376d98d1069d40a31113eb807/838ba61ea8d3fd1fc9c7b6853a4e251f94ca5f46.jpg",
        options: Options(responseType: ResponseType.bytes));
    final result = await ImageGallerySaverPlus.saveImage(
        Uint8List.fromList(response.data),
        quality: 60,
        name: "hello");
    print(result);
  }

  _saveNetworkGifFile() async {
    var appDocDir = await getTemporaryDirectory();
    String savePath = appDocDir.path + "/temp.gif";
    String fileUrl =
        "https://hyjdoc.oss-cn-beijing.aliyuncs.com/hyj-doc-flutter-demo-run.gif";
    await Dio().download(fileUrl, savePath);
    final result =
        await ImageGallerySaverPlus.saveFile(savePath, isReturnPathOfIOS: true);
    print(result);
  }

  _saveNetworkVideoFile() async {
    var appDocDir = await getTemporaryDirectory();
    String savePath = appDocDir.path + "/temp.mp4";
    String fileUrl =
        "https://s3.cn-north-1.amazonaws.com.cn/mtab.kezaihui.com/video/ForBiggerBlazes.mp4";
    await Dio().download(fileUrl, savePath, onReceiveProgress: (count, total) {
      print((count / total * 100).toStringAsFixed(0) + "%");
    });
    final result = await ImageGallerySaverPlus.saveFile(savePath);
    print(result);
  }
   */
static void saveImageUint8ListToPictures(
    Uint8List byteData,
  {
    int quality=100,
    String? name,
  }
    ) {
  ImageGallerySaver.saveImage(
      byteData,
    quality: quality,
    name:name
  );
}


}
